/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.mapper.UserRoleMapper;
import me.zhengjie.modules.system.rest.UserController;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.TeacherService;
import me.zhengjie.modules.system.domain.vo.TeacherQueryCriteria;
import me.zhengjie.modules.system.mapper.TeacherMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
* @description 服务实现
* @author tianjiaqi
* @date 2024-04-06
**/
@Service
@RequiredArgsConstructor
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    private final TeacherMapper teacherMapper;

    private final UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    private final UserRoleMapper userRoleMapper;

    private final UserService userService;

    private final UserController userController;

    @Override
    public PageResult<Teacher> queryAll(TeacherQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        criteria.setSchoolId(currentUser.getDeptId());
        PageResult<Teacher> teacherResults =  PageUtil.toPage(teacherMapper.findAll(criteria, page));

        List<Long> ids = new ArrayList<>();
        teacherResults.getContent().forEach(teach -> {
            if(teach.getUserid()!=null){
                ids.add(teach.getUserid());
            }

        });
        List<User> userList = new ArrayList<>();

        if(!ids.isEmpty()){
            userList = userMapper.selectBatchIds(ids);
        }
        List<User> finalUserList = userList;
        // 生成时间戳
        teacherResults.getContent().forEach(teachItem -> {
            finalUserList.forEach(user -> {
                if(teachItem.getUserid() == user.getId()){
                    teachItem.setUsername(user.getUsername());
                    teachItem.setNickName(user.getNickName());
                    teachItem.setAvatarName(user.getAvatarName());
                    teachItem.setPhone(user.getPhone());
                    teachItem.setEmail(user.getEmail());
                    teachItem.setGender(user.getGender());
                    teachItem.setEnabled(user.getEnabled());
                    teachItem.setCreatetime(String.valueOf(user.getCreateTime()));
                }
            });
        });
        return teacherResults;
    }

    @Override
    public List<Teacher> queryAll(TeacherQueryCriteria criteria){
        return teacherMapper.findAll(criteria);
    }


    @Override
    public List<User> getSchoolTeacher(TeacherQueryCriteria criteria) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("schoolId",currentUser.getDeptId());
        List<Teacher> list = teacherMapper.selectList(queryWrapper);
        List<Long> ids = new ArrayList<>();
        for(Teacher teacher:list){
            ids.add(teacher.getUserid());
        }

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("user_id",ids);
        if(!ids.isEmpty()){
            return userMapper.selectList(queryWrapper1);
        } else {
            return null;
        }

    }
    public Map<String,Object> checkTeacher(Teacher resources) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        resources.setSchoolid(currentUser.getDeptId());
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",resources.getUsername());
        User currentUser2 = userMapper.selectOne(queryWrapper1);

        Map<String,Object> map = new HashMap<>();
        map.put("number",resources.getNumber());
        map.put("numberType",null);

        map.put("name",resources.getUsername());
        map.put("nameType",null);

        if(resources.getUsername() == null){
            map.put("nameType","登录名不能为空");
        }

        map.put("username",resources.getUsername());
        map.put("usernameType",null);

        if(resources.getUsername() == null){
            map.put("nameType","登录名不能为空");
        }

        map.put("nickName",resources.getNickName());

        if(resources.getNickName() == null){
            map.put("nickNameType","姓名不能为空");
        }

        map.put("email",resources.getEmail());
        map.put("emailType",null);

        map.put("phone",resources.getPhone());
        map.put("phoneType",null);

        map.put("gender",resources.getGender());
        map.put("genderType",null);

        map.put("avatarPath",resources.getAvatarPath());
        map.put("password",resources.getPassword());
        map.put("status",0);

        if(!String.valueOf(resources.getGender()).equals("男") && !String.valueOf(resources.getGender()).equals("女")){
            map.put("genderType","性别信息智能为男或女");
        }

        if(currentUser2!=null){

            map.put("usernameType","用户名重复");
            map.put("status",1);
        }

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && repeatEmailUser.getId() != resources.getUserid()){

            map.put("emailType","邮箱重复");
            map.put("status",1);
        }

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && repeatPhoneUser.getId() != resources.getUserid()){
//            return -4;
            map.put("phoneType","手机号重复");
            map.put("status",1);
        }
        if(resources.getEmail() != null){
            if(!validateEmail(resources.getEmail())){
                map.put("emailType","邮箱格式错误");
                map.put("status",1);
            }
        } else {
            map.put("emailType","邮箱格式为空");
            map.put("status",1);
        }


        if(resources.getPhone() != null){
            if(!validatePhoneNumber(resources.getPhone())){
                map.put("phoneType","手机号格式错误");
                map.put("status",1);
            }
        } else {
            map.put("phoneType","手机号不能为空");
            map.put("status",1);
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Teacher repeatStudentUser =  teacherMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null && resources.getId()!=repeatStudentUser.getId()){

            map.put("numberType","工号重复");
            map.put("status",1);
        }

        return map;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer create(Teacher resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        resources.setSchoolid(currentUser.getDeptId());
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",resources.getUsername());
        User currentUser2 = userMapper.selectOne(queryWrapper1);
        if(currentUser2!=null){
            return -3;
        }
        User user = new User();
        user.setUsername(resources.getUsername());
        user.setNickName(resources.getNickName());
        user.setDeptId(currentUser.getDeptId());
        user.setAvatarName(resources.getAvatarName());
        user.setAvatarPath(resources.getAvatarPath());

        user.setEmail(resources.getEmail());
        user.setPhone(resources.getPhone());
        user.setEnabled(resources.getEnabled());
        user.setGender(resources.getGender());

        user.setType(1);


        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && repeatEmailUser.getId() != resources.getUserid()){
            return -1;
        }

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && repeatPhoneUser.getId() != resources.getUserid()){
            return -4;
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Teacher repeatStudentUser =  teacherMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null && resources.getId()!=repeatStudentUser.getId()){
            return -5;
        }
        Set<Job> jobs = new HashSet<>();
        Job job = new Job();
        job.setId(11L);
        jobs.add(job);
        user.setJobs(jobs);

        Set<Role> roles = new HashSet<>();
        Role role = new Role();
        role.setId(5L);
        roles.add(role);
        user.setRoles(roles);

        Dept dept = new Dept();
        dept.setId(currentUser.getDeptId());
        user.setDept(dept);

        user.setPassword(passwordEncoder.encode(resources.getPassword()));
        userService.create(user);

        resources.setUserid(user.getId());
        resources.setName(resources.getUsername());
        save(resources);

        return 1;
    }


    public Integer create2(Teacher resources) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        resources.setSchoolid(currentUser.getDeptId());
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",resources.getUsername());
        User currentUser2 = userMapper.selectOne(queryWrapper1);
        if(currentUser2!=null){
            return -3;
        }
        User user = new User();
        user.setUsername(resources.getUsername());
        user.setNickName(resources.getNickName());
        user.setDeptId(currentUser.getDeptId());
        user.setAvatarName(resources.getAvatarName());
        user.setAvatarPath(resources.getAvatarPath());

        user.setEmail(resources.getEmail());
        user.setPhone(resources.getPhone());
        user.setEnabled(resources.getEnabled());
        user.setGender(resources.getGender());

        user.setType(1);


        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && repeatEmailUser.getId() != resources.getUserid()){
            return -1;
        }

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && repeatPhoneUser.getId() != resources.getUserid()){
            return -4;
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Teacher repeatStudentUser =  teacherMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null && resources.getId()!=repeatStudentUser.getId()){
            return -5;
        }
        Set<Job> jobs = new HashSet<>();
        Job job = new Job();
        job.setId(11L);
        jobs.add(job);
        user.setJobs(jobs);

        Set<Role> roles = new HashSet<>();
        Role role = new Role();
        role.setId(5L);
        roles.add(role);
        user.setRoles(roles);

        Dept dept = new Dept();
        dept.setId(currentUser.getDeptId());
        user.setDept(dept);

        user.setPassword(passwordEncoder.encode(resources.getPassword()));
        userService.create(user);

        resources.setUserid(user.getId());
        resources.setName(resources.getUsername());
        save(resources);

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(Teacher resources) throws Exception {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",resources.getEmail());
        User repeatEmailUser =  userMapper.selectOne(queryWrapper);
        if(repeatEmailUser!= null && repeatEmailUser.getId() != resources.getUserid()){
            return -1;
        }

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone",resources.getPhone());
        User repeatPhoneUser =  userMapper.selectOne(queryWrapper2);
        if(repeatPhoneUser!= null && repeatPhoneUser.getId() != resources.getUserid()){
            return -4;
        }

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("number",resources.getNumber());
        Teacher repeatStudentUser =  teacherMapper.selectOne(queryWrapper3);
        if(repeatStudentUser!= null && resources.getId()!=repeatStudentUser.getId()){
            return -5;
        }


        Teacher teacher = getById(resources.getId());
        teacher.setName(resources.getUsername());
        teacher.copy(resources);
        saveOrUpdate(teacher);

        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("user_id",resources.getUserid());
        User user = userMapper.selectOne(queryWrapper5);
        user.setUsername(resources.getUsername());
        user.setNickName(resources.getNickName());
        user.setAvatarName(resources.getAvatarName());
        user.setAvatarPath(resources.getAvatarPath());

        user.setEmail(resources.getEmail());
        user.setPhone(resources.getPhone());
        user.setEnabled(resources.getEnabled());
        user.setGender(resources.getGender());
//        userMapper.update(user,queryWrapper);

        Set<Job> jobs = new HashSet<>();
        Job job = new Job();
        job.setId(11L);
        jobs.add(job);
        user.setJobs(jobs);

        Set<Role> roles = new HashSet<>();
        Role role = new Role();
        role.setId(5L);
        roles.add(role);
        user.setRoles(roles);

        Dept dept = new Dept();
        dept.setId(currentUser.getDeptId());
        user.setDept(dept);
//        userService.update(user);

//        user.setPassword(passwordEncoder.encode(resources.getPassword()));
//        QueryWrapper queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("user_id",resources.getId());
        userService.update(user);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {

        List<Teacher> list = teacherMapper.selectBatchIds(ids);
        List<Integer> teacherIds = new ArrayList<>();
        for(Teacher teacher : list){
            teacherIds.add(Math.toIntExact(teacher.getUserid()));
        }
        userMapper.deleteBatchIds(teacherIds);
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Teacher> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Teacher teacher : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("工号", teacher.getNumber());
            map.put(" userid",  teacher.getUserid());
            map.put("教师名称", teacher.getName());
            map.put(" lastupdatetime",  teacher.getLastupdatetime());
            map.put(" createtime",  teacher.getCreatetime());
            map.put("组织id", teacher.getSchoolid());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    //验证邮箱
    public static boolean validateEmail(String email) {
        // 定义匹配邮箱的正则表达式
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
    //验证手机号
    public static boolean validatePhoneNumber(String phoneNumber) {
        // 定义匹配手机号的正则表达式，这里以1开头，后面跟10位数字为例（简单通用情况）
        String regex = "^1[0-9]{10}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);
        return matcher.matches();
    }
}